﻿using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Http;

namespace BPanel.Core.Middlewares;

public class UnifiedResponseMiddleware
{
    private readonly RequestDelegate _next;

    public UnifiedResponseMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // 这里可以放置处理请求的逻辑
        try
        {
            // 调用下一个中间件
            await _next(context);

            if (context.Response.StatusCode == 401)
            {
                var response = new ApiResponse()
                {
                    Success = false,
                    StatusCode = 401,
                    Message = "认证信息异常"
                };

                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)HttpStatusCode.OK;

                await context.Response.WriteAsync(JsonSerializer.Serialize(response, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                }));
            }
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static async Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        var response = new ApiResponse()
        {
            Success = false,
            StatusCode = -1,
            Message = ex.Message
        };

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.OK;

        await context.Response.WriteAsync(JsonSerializer.Serialize(response, new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        }));
    }
}